<?php

namespace app\controller\student;

use app\BaseController;
use app\model\StudentCourse;
use app\model\Exam;
use app\model\Question;
use app\model\StudentExam as ModelStudentExam;
use \think\facade\Db;

/**
 * 学生测验控制器
 */
class StudentExam extends BaseController
{

    /**
     * 测试列表
     */
    public function list()
    {
        $courseID = $this->request->param('courseID');
        $studentCourse = StudentCourse::where(["SID" => $this->user['SID'], "courseID", $courseID]);
        if (empty($studentCourse)) {
            return json("no permission");
        }
        $examList = Exam::field(['EID','courseID','title','type','startTime','endTime','credit','status'])->where(["courseID" => $courseID])->select()->toArray();
        foreach($examList as $key=>$exam){
            if(ModelStudentExam::where(['SID'=>$this->user['SID'],'EID'=>$exam['EID']])->find()){
                $examList[$key]['isSubmit'] = true;
            }else{
                $examList[$key]['isSubmit'] = false;
            }
        }
        //return json($examList);
        return resultSuccess($examList);
    }

    /**
     * 获取测试内容
     */
    public function getExamDetail()
    {
        $EID = $this->request->param("EID");
        $exam = Exam::where(["EID"=> $EID])->find();
        if(empty($exam)) {
            return resultError("查无此测验");
        }
        //查无此测试
        if(strtotime($exam->endTime) <strtotime("now") || strtotime($exam->startTime) > strtotime("now") ){
            return resultError("无此权限");
        }
        //测试已结束或未开始
        $studentCourse = StudentCourse::where(["SID" => $this->user['SID'], "courseID"=> $exam['courseID']])->find();
        if (empty($studentCourse)) {
            return resultError("无此权限");
        }
        //权限验证
        $QIDList = array_column((array)$exam['questions'], 'QID');
        $QIDWithScoreList = array_combine($QIDList, (array)$exam['questions']);
        //为测验问题数组添加索引
        $questionList = Question::select($QIDList)->toArray();
        $totalScore = 0; //定义问题总分
        foreach ($questionList as $key => $question) {
            $questionList[$key]['score'] = $QIDWithScoreList[$question['QID']]['score'];
            $totalScore += $questionList[$key]['score']; //获取所有存在的问题的总分
        } //将分数放入获取出来的题目数组
        $QIDList = array_column((array)$exam['questions'], 'QID');
        //$questionList = array_combine($QIDList, $questionList);
        foreach($questionList as $key=>$question){
            $questionList[$key]['answer'] = null;
        }
        $examDetail = $exam->toArray();
        $examDetail['questions'] = array_values($questionList);
        $preAnswer =ModelStudentExam::where(['SID'=>$this->user['SID'],'EID'=>$EID])->find();
        if($preAnswer){
           $examDetail['preAnswer'] = $preAnswer->answer;
        }
        return resultSuccess(
            $examDetail
        );

    }

    /**
     * 提交答案
     */
    public function submitExam()
    {
        $EID = $this->request->param("EID");
        $exam = Exam::where("EID", $EID)->find();
        if(empty($exam)) {
            return resultError("查无此测验");
        }
        //查无此测试
        if($exam->endTime < time() && $exam->startTime > time() ){
            return resultError("无此权限");
        }
        //测试已结束或未开始
        $studentCourse = StudentCourse::where(["SID" => $this->user['SID'], "courseID"=> $exam['courseID']]);
        if (empty($studentCourse)) {
            return resultError("无此权限");
        }
        //权限验证
        $QIDList = array_column((array)$exam['questions'], 'QID');
        $QIDWithScoreList = array_combine($QIDList, (array)$exam['questions']);
        //为测验问题数组添加索引
        $questionList = Question::select($QIDList)->toArray();
        $totalScore = 0; //定义问题总分
        foreach ($questionList as $key=>$question) {
            $questionList[$key]['score'] = $QIDWithScoreList[$question['QID']]['score'];
            $totalScore += $questionList[$key]['score']; //获取所有存在的问题的总分
        } //将分数放入获取出来的题目数组
        $QIDList = array_column((array)$questionList, 'QID');
        $questionList = array_combine((array)$QIDList, (array)$questionList);
        //为问题数组添加索引
        $studentExam = $this->request->param('studentExam');
        //获取学生作答信息
        $studentAnswerList = $studentExam;
        $correction = [
            'totalScore' => 0
        ];
        foreach ($studentAnswerList as $studentAnswer) {
            $QID = $studentAnswer['QID'];
            if (isset($questionList[$QID])) {
                //是否存在该问题
                if(!is_array($studentAnswer['answer'])){
                    $studentAnswer['answer']= [$studentAnswer['answer']];
                }
                if ($questionList[$QID]['type']!=4 && sizeof(array_diff((array)$questionList[$QID]['answer'], (array)$studentAnswer['answer']))==0) {
                    $correction['totalScore'] += $questionList[$QID]['score'];
                    //添加总分
                    $correction['detail'][] = [
                        'QID' => $QID,
                        'isCorrect' => true,
                        'score' => $questionList[$QID]['score']
                    ];
                } else {
                    $correction['detail'][] = [
                        'QID' => $QID,
                        'isCorrect' => false,
                        'score' => 0
                    ];
                }
            }
            //判断题目是否正确并存入判题数组
        }
        $credit = floor($exam['credit'] * $correction['totalScore'] / $totalScore);
        $studentExam = new ModelStudentExam(['correction' => $correction, 'answer'=>$studentAnswerList,'credit' => $credit,'SID' => $this->user['SID'], 'EID' => $EID]);
        $save = $studentExam->replace()->save();
        //保存当前学生-测验数据
        if ($save == false) {
            return resultError("保存错误");
        }
        return resultSuccess();
    }

    /**
     * 查询解析
     */
   /**
     * 获取单个学生测试详情
     */
    public function getScore()
    {
        $EID = $this->request->param("EID");
        $SID = $this->user['SID'];
        $studentExam = ModelStudentExam::where(["EID" => $EID, 'SID' => $SID])->find();
        if (empty($studentExam)) {
            return resultError('未参加此测试');
        }
        $exam = Exam::where(["EID"=> $EID])->find();
        //此处判断该教师是否有权限
        $QIDList = array_column((array)$exam['questions'], 'QID');
        $QIDWithScoreList = array_combine($QIDList, (array)$exam['questions']);
        //为测验问题数组添加索引
        $questionList = Question::select($QIDList)->toArray();
        $totalScore = 0; //定义问题总分
        foreach ($questionList as $key=>$question) {
            $questionList[$key]['score'] = $QIDWithScoreList[$question['QID']]['score'];
            $totalScore += $questionList[$key]['score']; //获取所有存在的问题的总分
        } //将分数放入获取出来的题目数组
        $QIDList = array_column((array)$exam['questions'], 'QID');
        sort($QIDList);
        $questionList = array_combine((array)$QIDList, (array)$questionList);
        // $studentExam = ModelStudentExam::where(["EID" => $exam['EID'], 'SID' => $SID])->find();
        //为问题数组添加索引
        return resultSuccess([
            'studentExam' => $studentExam,
            'questionList' => $questionList
        ]);
    }
}
